package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 消费者
 */
@RocketMQMessageListener(
        consumerGroup = MQConstants.ORDER_SUCCESS_DELAY_GROUP,
        topic = MQConstants.SECKILL_ORDER,
        selectorType = SelectorType.TAG,
        selectorExpression = MQConstants.ORDER_SUCCESS_DELAY_TAG
)
@Component
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Override
    public void onMessage(Map map) {
        Long seckillId = (Long) map.get("seckillId");

        String orderNo=map.get("data").toString();
        Object obj =  map.get("goodId");
        Long goodId=null;
        //根据不同的类型做处理
        if(obj instanceof  Long){
            goodId=(Long)obj;
        }else if(obj instanceof  Integer){
            goodId=((Integer)((Integer) obj)).longValue();
        }
        //查看是否支付
        //未支付，把状态改为超时支付
        int count=orderInfoService.changOrderInfoStatus(orderNo, OrderInfo.STATUS_TIMEOUT);
       if (count>0){
           //回补真实库存

           seckillGoodService.incrCount(seckillId);
           //回补预支付
           seckillGoodService.syncRedisCount(goodId);
           //修改本地标识
           rocketMQTemplate.syncSend(MQConstants.ORDER_FAIL_NOTIFY_DEST,goodId);

       }

    }
}
